package org.uek.ships.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uek.shpis.common.Configuration;

public class Server {

	private static Logger logger = LoggerFactory.getLogger(Server.class);

	public static void main(String[] args) {
		ServerSocket server = null;
		PlayerPair playerPair = null;
		try {

			server = new ServerSocket(Configuration.PORT);
			logger.info("Serwer uruchomiony ...");

			while (true) {

				Socket playerSocket = server.accept();

				if (playerSocket != null) {
					logger.info("Uzytkownik polaczony : " + playerSocket.getLocalAddress());
					if (playerPair == null) {
						playerPair = new PlayerPair(playerSocket);
					} else {
						logger.info("Drugi uzytkownik polaczony : " + playerSocket.getLocalAddress());
						playerPair.setSecondPlayerSocket(playerSocket);

						GameThread gameThread = new GameThread(playerPair);
						playerPair = null;
						logger.info("Drugi uzytkownik polaczony start gry");
						gameThread.run();
					}
				}

			}

		} catch (Exception e) {
			logger.error("Wystapil bald: ", e);
		} finally {
			if (server != null) {
				try {
					server.close();
				} catch (IOException e) {
				}
			}
		}
	}
}
